/*
 * @Descripttion: 
 * @Author: Silence
 * @Date: 2023-06-03 19:47:05
 * @LastEditors: Silence
 * @LastEditTime: 2023-06-03 20:28:53
 */
import axios from 'axios'
export default {
  state () {
    return {
      list: []
    }
  },
  mutations: {
    changeList (state, list) {
      state.list = list
    },
    changeCount (state, obj) {
      state.list.find(item => item.id === obj.id).count = obj.count
    }
  },
  actions: {
    async getList ({ commit }) {
      const res = await axios.get('http://localhost:3000/cart')
      commit('changeList', res.data)
    },
    // syncCount ({ commit }, obj) {
    //   return new Promise(async (resolve, reject) => {
    //     const res = await axios.get('http://localhost:3000/cart/' + obj.id, { count: obj.count })
    //     resolve(res)
    //   })
    // }
    syncCount ({ commit }, obj) {
      axios.get('http://localhost:3000/cart/' + obj.id, { count: obj.count })
      commit('changeCount', obj)
    }
  },
  getters: {
    totalcount (state) {
      return state.list.reduce((sum, item) => sum + item.count, 0)
    },
    totalprice (state) {
      return state.list.reduce((sum, item) => sum + item.count * item.price, 0)
    }
  },
  namespaced: true
}
